/*************************************************
* Title：TinyToolKit
* Author：Opportunity 
* Describe：默认的二进制序列化模板
* CreateTime：2020-12-16 18:00:18
* Version：1.0
* Modify Recorder：
*************************************************/

using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace TinyToolKit
{
    public class DefaultBinaryTemplate : TinyUtility.Binary.IBinaryTemplate
    {
        public bool BinarySerialize(string filePath, object obj) 
        {
            string dirPath = Path.GetDirectoryName(filePath);
            if (string.IsNullOrEmpty(dirPath) == false && Directory.Exists(dirPath) == false)
                Directory.CreateDirectory(dirPath);
            
            using (FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate))
            {
                BinaryFormatter bf = new BinaryFormatter();
                bf.Serialize(fs, obj);
                return true;
            }
        }

        public object BinaryDeserialize(byte[] bytes)
        {
            using (MemoryStream memoryStream = new MemoryStream(bytes, false))
            {
                return BinaryDeserialize(memoryStream);
            }
        }

        public object BinaryDeserialize(Stream stream)
        {
            using (stream)
            {
                BinaryFormatter bf = new BinaryFormatter();
                return bf.Deserialize(stream);
            }
        }

        public object BinaryDeserialize(string filePath)
        {
            var fileInfo = new FileInfo(filePath);

            if (!fileInfo.Exists)
            {
                TLogTool.Error("反序列化文件不存在：" + filePath);
                return null;
            }

            using (var fs = fileInfo.OpenRead())
            {
                BinaryFormatter bf = new BinaryFormatter();
                return bf.Deserialize(fs);
            } 
        }
    }
}

